package Client.Dropbox.Communication

import Client.Dropbox.Manager.FileManager
import java.net.URL
import java.io.BufferedReader
import java.io.InputStreamReader
import scala.actors.remote.Node

/**
 * Class that the server notifies when there is an update
 */
object UpdateNotifier extends Thread{
  var reciever = null.asInstanceOf[UpdateReciever]
  var serv=null.asInstanceOf[String]
  var stopping=false
  
  /**
   * 
   * Initialize update receiver and start running
   * @param port the port with which the actor connects to the server
   * @param serv the server
   * @param servPort the server's port
   */
  def init (port:Int, serv:String, servPort:Int) {
    this.serv=serv
    reciever=new UpdateReciever (port, Node(serv, servPort))
    start
  }
  
  /**
   * Stop running in an organized fashion
   */
  def stopRunning = {
    reciever ! "Done"
    stopping=true
  }
  
  /**
   * Run method for the thread
   */
  override def run {
    val address = "http://"+serv+":1111/login?UID="+FileManager.user +"&CID="+FileManager.client ////not the right address!!!!!
      try {
        //connect to server
        val url = new URL(address)
        val in = new BufferedReader(new InputStreamReader(url.openStream()))
        var inputLine=""
        reciever.start
        do {
          //read message from server
    	  inputLine = in.readLine
    	  if (inputLine!=null)
    	  {
       	    println("Update Notifier received: "+inputLine)
      	    //server should be notifying of a new update, and if so, go receive the messages
            if (inputLine.equals("New Update"))
        	  reciever.restart
    	  }
        }while (inputLine != null && !stopping)
        in.close();    
      } catch {
        case e:Exception => System.err.println(e.getMessage)
      }
  }
}